using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework;

namespace MIMPWinForms.XnaControls
{
    public class XnaSpriteViewerControl : GraphicsDeviceControl
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private ContentManager content;
        private SpriteBatch spriteBatch;

        private Texture2D sprite;
        private Texture2D blank;

        private Rectangle bounds;
        private Color color;

        private string spritename;
        /// <summary>
        /// The name of the content file containing the sprite that this control draws. 
        /// When this property is set, the XnaSpriteViewerControl loads the texture file
        /// using the ContentManager.
        /// If the SetSprite method is used to set the sprite, then this property returns an empty string.
        /// </summary>
        public string SpriteContentName {
            get { return spritename; }
            set {
                spritename = value;
                if (content != null) {
                    sprite = content.Load<Texture2D>(spritename);
                    this.Invalidate();
                }
            }
        }

        /// <summary>
        /// Directly sets the sprite drawn by this XnaSpriteViewerControl. To have the control load 
        /// a texture file dynamically, use the SpriteContentName property.
        /// </summary>
        public void SetSprite(Texture2D sprite) {
            if (log.IsInfoEnabled) log.Info("Entered SetSprite");
            if (log.IsDebugEnabled) log.Debug("Name of sprite passed in: " + sprite.Name);
            this.spritename = "";
            this.sprite = sprite;
            if (log.IsInfoEnabled) log.Info("Exiting SetSprite");
        }

        protected override void Initialize() {
            color = Constants.SysColorToXnaColor(this.BackColor);
            bounds = new Rectangle(0, 0, this.Size.Width, this.Size.Height);
            content = new ContentManager(Services, "Content");
            spriteBatch = new SpriteBatch(GraphicsDevice);
            blank = content.Load<Texture2D>(Constants.CONTENT_BLANK);
            if (!String.IsNullOrEmpty(spritename)) {
                sprite = content.Load<Texture2D>(spritename);
            }
        }

        protected override void GameUpdate() {
        }

        protected override void Draw() {
            spriteBatch.Begin();
            spriteBatch.Draw(blank, bounds, color);
            if (sprite != null) {
                spriteBatch.Draw(sprite, bounds, Color.White);
            }
            spriteBatch.End();
        }
    }
}
